﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;

using OfficeSVN;


namespace ExcelSVN {

    public partial class ThisAddIn: IOfficePlugIn {

        public static Excel.Application ExcelApplication;
        public static OfficeSvnRibbon ExcelRibbon;
        private static SubversionController _controller;

        private void ThisAddIn_Startup(object sender, System.EventArgs e) {

            ExcelApplication = this.Application;
            Globals.ThisAddIn.Application.WorkbookActivate += Application_WorkbookActivate;

            _controller = new SubversionController(this);
        }

        public override void BeginInit()
        {
            _controller = new SubversionController(this);

            base.BeginInit();
        }

        protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject() {

            if (_controller != null)
                return _controller.GetRibbon();

            return null;
        }
       
        void Application_WorkbookActivate(Microsoft.Office.Interop.Excel.Workbook workbook) {
            OnDocumentChangedEvent(workbook.FullName);
        }

        private void OnDocumentChangedEvent(string document)
        {
            // Copy to a temporary variable to be thread-safe.
            EventHandler<DocumentEventArgs> temp = DocumentChanged;
            if (temp != null)
                temp(null, new DocumentEventArgs(document));
        }

        public event EventHandler<DocumentEventArgs> DocumentChanged;

        public void OpenDocument(string document)
        {
            Object Missing = System.Reflection.Missing.Value;

            ExcelApplication.Workbooks.Open(document, Missing, Missing, Missing, Missing, Missing, Missing, Missing, Missing, Missing, Missing, Missing, Missing, Missing, Missing);
        }

        public void CloseDocument(string document)
        {
            ExcelApplication.ActiveWorkbook.Close(null, null, null);
        }

        public void SaveDocument(string document)
        {
            ExcelApplication.ActiveWorkbook.Save();
        }

        public void ReloadDocument(string document)
        {
            // This does not work properly, the readonly-flag would not be removed/set
            // ExcelApplication.ActiveWorkbook.ReloadAs(Office.MsoEncoding.msoEncodingAutoDetect);

            CloseDocument(document);
            OpenDocument(document);
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup() {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
        }
    }
}
